<?php
namespace app\component\controller;

use app\common\base\BasicRest;
use think\Config;
use think\Db;
use think\Request;
use think\Cache;

class Wechatlogin extends  BasicRest
{

    public function __construct()
    {
        parent::__construct();
    }

    protected function validatecsrf(){
        // $csrf=$this->request->post('_CSRF');
        // if($csrf&&strlen($csrf)==12){
        //     $onedata=substr($csrf,0,4);
        //     $twodata=substr($csrf,4,4);
        //     $threedata=substr($csrf,8,4);
        //     $result= substr((string)((int)$onedata*(int)$threedata),0,4);
        //     if($result!=$twodata){
        //         echo '非法请求';
        //         exit(0);
        //     }
        // }else{
        //     echo '非法请求';
        //         exit(0);
        // }
         
    }
        
    public function wechatlogin($redirect_uri){
        $appid=Config::get('wechatAppappidlogin');
        $codeurl = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=$appid&redirect_uri=$redirect_uri&response_type=code&scope=snsapi_base&state=123#wechat_redirect";
        return $this->redirect($codeurl);
    }

    //获取用户openid
    public function wechatgetopenid(){
        $data=$this->request->get();
        $code=$data['code'];
        $state=$data['state'];
        $coderror=[];
        for($i=10003;$i<10017;$i++){
            $codeerror[]=$i;
        }
        //如果错误了
        if(in_array($code,$codeerror)){
            echo "错误:$code";
        }
        $appid=Config::get('wechatAppappidlogin');
        $wechatSecret=Config::get('wechatSecretlogin');
        $accessurl="https://api.weixin.qq.com/sns/oauth2/access_token?appid=$appid&secret=$wechatSecret&code=$code&grant_type=authorization_code";

                    $curl = curl_init();
                    curl_setopt($curl, CURLOPT_URL, $accessurl);
                    // curl_setopt($curl, CURLOPT_HEADER, 1);
                    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
                    $data = curl_exec($curl);
                    curl_close($curl);
                    $data=json_decode($data,true);

                if(isset($data['errcode'])){
                    return  ['status'=>false,'msg'=>"错误:".$data['errmsg']];
                    
                }else{
                    //获取到了openid 
                    return ['status'=>true,'openid'=>$data['openid']];
                }
        
    }
  
}